package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/report/constant"
	"github.com/lab-online/internal/report/entity"
	"github.com/lab-online/pkg/auth"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
	"github.com/lab-online/pkg/util"
)

type searchReportReqQuery struct {
	ID           uint   `form:"id" binding:"omitempty,min=1" example:"1"`                   // 报告ID
	ClassID      uint   `form:"classID" binding:"omitempty,min=1" example:"1"`                // 班级ID
	ExperimentID uint   `form:"experimentID" binding:"omitempty,min=1" example:"1"`           // 实验ID
	Student      string `form:"student" binding:"omitempty,min=8,max=8" example:"20240205"` // 学生学号
}

var SearchReportValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Query: &searchReportReqQuery{},
	}
})

type SearchReportRespBody struct {
	resp.BaseRespBody
	Data []reportInfo `json:"data" binding:"required"`
}

// SearchReport 搜索报告
//
//	@Summary				搜索报告
//	@Description.markdown	SearchReport
//	@Tags					report
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string					true	"`all`"
//	@Param					report			query		searchReportReqQuery	true	"报告信息"
//	@Success				200				{object}	SearchReportRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@Router					/v1/reports     [get]
func (h *Handler) SearchReport(c *gin.Context) {
	query := c.MustGet(mw.KeyQuery).(*searchReportReqQuery)
	authEntity := c.MustGet(auth.KeyAuth).(auth.AuthEntity)

	reportEntity := entity.New(
		entity.WithID(query.ID),
		entity.WithExperimentID(query.ExperimentID),
		entity.WithClassID(query.ClassID),
		entity.WithStudent(query.Student),
	)

	if reports, err := h.domain.SearchReport(authEntity, reportEntity); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success(c, constant.CodeSearchReportSuccess, util.SliceMap(
			reports, func(report entity.ReportEntity) *reportInfo {
				return &reportInfo{
					ID:           report.GetID(),
					ExperimentID: report.GetExperimentID(),
					ClassID:      report.GetClassID(),
					Student:      report.GetStudent(),
					Score:        report.GetScore(),
					Status:       report.GetStatus(),
				}
			}),
		)
	}
}
